﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using System.Data;

namespace RandomClick
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private enum WorkflowStep
        {
            SelectTarget,
            FillAndLogin,
            BookLike,
            NavigateLogout,
            NavigateTarget,
            FinishTarget,
            NavigateActiveLink,
            NavigateHome,
        }

        private class WorkflowStepInfo
        {
            public WorkflowStep Step { get; set; }
            public bool WaitBrowserLoaded { get; set; }
            public int TimerFactor { get; set; }

            public WorkflowStepInfo()
            {
                this.Step = WorkflowStep.SelectTarget;
                this.WaitBrowserLoaded = false;
                this.TimerFactor = 1;
            }

            public WorkflowStepInfo(WorkflowStep step, bool waitLoaded, int factor)
            {
                this.Step = step;
                this.WaitBrowserLoaded = waitLoaded;
                this.TimerFactor = factor;
            }
        }

        private List<RandomClickDataSet.useruriRow> listUseruri = new List<RandomClickDataSet.useruriRow>();
        private List<WorkflowStepInfo> listWorkflowStep = new List<WorkflowStepInfo>();
        private int currentWorkflowStepIndex = -1;
        private int currentWorkItemIndex = -1;

        private string taskMode = string.Empty;

        private bool webBrowserLoaded = false;
        private bool toStop = false;

        private DispatcherTimer timer;

        private string username = string.Empty;
        private string password = string.Empty;
        private string activeLink = string.Empty;
        private string targetUri = string.Empty;

        RandomClickDataSet.userDataTable userTable = new RandomClickDataSet.userDataTable();
        RandomClickDataSet.uriDataTable uriTable = new RandomClickDataSet.uriDataTable();
        RandomClickDataSet.useruriDataTable useruriTable = new RandomClickDataSet.useruriDataTable();

        public MainWindow()
        {
            InitializeComponent();

            DataObject.AddPastingHandler(this.textBoxUsernumber, new DataObjectPastingEventHandler(this.TextBoxPastingEventHandler));
            DataObject.AddPastingHandler(this.textBoxTimerInterval, new DataObjectPastingEventHandler(this.TextBoxPastingEventHandler));

            RandomClickDataSetTableAdapters.userTableAdapter userAdapter =
                new RandomClickDataSetTableAdapters.userTableAdapter();
            this.userTable = userAdapter.GetData();
            this.labelUserCount.Content = this.userTable.Rows.Count;

            RandomClickDataSetTableAdapters.uriTableAdapter uriAdapter =
                new RandomClickDataSetTableAdapters.uriTableAdapter();
            this.uriTable = uriAdapter.GetData();

            RandomClickDataSetTableAdapters.useruriTableAdapter useruriAdapter =
                new RandomClickDataSetTableAdapters.useruriTableAdapter();
            this.useruriTable = useruriAdapter.GetDataByUristate(Properties.Resources.UriStateTodo);

            this.InitailWorkflow();

            if (Properties.Settings.Default.DebugMode)
            {
                this.stackPanelDebug.Visibility = Visibility.Visible;
            }
            else
            {
                this.stackPanelDebug.Visibility = Visibility.Collapsed;
            }
        }

        private void InitailWorkflow()
        {
            this.listWorkflowStep.Clear();
            this.listWorkflowStep.Add(new WorkflowStepInfo(WorkflowStep.SelectTarget, false, 1));
        }

        private List<WorkflowStepInfo> GetMeilishuoBookLikeUsernamePasswordWorkflow()
        {
            List<WorkflowStepInfo> listWFStep = new List<WorkflowStepInfo>();
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.SelectTarget, false, 1));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.NavigateLogout, false, 4));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.NavigateTarget, false, 4));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.BookLike, false, 1));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.FillAndLogin, false, 4));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.NavigateHome, false, 2));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.NavigateTarget, false, 4));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.BookLike, false, 1));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.FinishTarget, false, 1));
            return listWFStep;
        }

        private List<WorkflowStepInfo> GetMeilishuoBookLikeActiveLinkWorkflow()
        {
            List<WorkflowStepInfo> listWFStep = new List<WorkflowStepInfo>();
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.SelectTarget, false, 1));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.NavigateLogout, false, 4));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.NavigateActiveLink, false, 4));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.NavigateHome, false, 2));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.NavigateTarget, false, 4));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.BookLike, false, 1));
            listWFStep.Add(new WorkflowStepInfo(WorkflowStep.FinishTarget, false, 1));
            return listWFStep;
        }

        private void MeilishuoCheckUriUsernamePasswordWorkflow()
        {
            this.listWorkflowStep.Clear();
        }

        private void MeilishuoCheckUriActiveLinkWorkflow()
        {
            this.listWorkflowStep.Clear();
        }

        private void BookLike()
        {
            mshtml.HTMLDocument doc = this.webBrowser.Document as mshtml.HTMLDocument;
            mshtml.IHTMLElementCollection anchors = doc.anchors;
            foreach (mshtml.IHTMLElement anchorElement in anchors)
            {
                mshtml.HTMLAnchorElement anchor = anchorElement as mshtml.HTMLAnchorElement;
                if (anchor != null)
                {
                    string outerHTML = anchor.outerHTML;
                    if (outerHTML.Contains(Properties.Resources.InputBookLike))
                    {
                        anchor.click();
                    }
                }
            }
        }

        private void NavigateTargetPage(string targetUri)
        {
            this.webBrowser.Navigate(new Uri(targetUri, UriKind.RelativeOrAbsolute));
        }

        private void NavigateLoginPage()
        {
            this.webBrowser.Navigate(new Uri(Properties.Resources.MeilishuoLoginUri, UriKind.RelativeOrAbsolute));
        }

        private void FillAndLogin(string username, string password)
        {
            mshtml.HTMLDocument doc = this.webBrowser.Document as mshtml.HTMLDocument;
            mshtml.HTMLInputElement inputUserName = doc.getElementById(Properties.Resources.InputUserNameID) as mshtml.HTMLInputElement;
            mshtml.HTMLInputElement inputPassword = doc.getElementById(Properties.Resources.InputPasswordID) as mshtml.HTMLInputElement;
            if (inputUserName != null && 
                inputPassword != null &&
                inputUserName.name.Equals(Properties.Resources.InputUserNameName, StringComparison.OrdinalIgnoreCase) &&
                inputPassword.name.Equals(Properties.Resources.InputPasswordName, StringComparison.OrdinalIgnoreCase))
            {
                inputUserName.value = username;
                inputPassword.value = password;

                mshtml.IHTMLElement loginFormElement = doc.getElementById(Properties.Resources.InputLogonForm);
                mshtml.HTMLFormElement loginForm = loginFormElement as mshtml.HTMLFormElement;
                if (loginForm != null)
                {
                    mshtml.IHTMLElementCollection loginFormInputCollection = loginForm.getElementsByTagName(Properties.Resources.InputInput);
                    if (loginFormInputCollection != null)
                    {
                        foreach (mshtml.IHTMLElement inputElement in loginFormInputCollection)
                        {
                            mshtml.HTMLInputButtonElement inputSubmit = inputElement as mshtml.HTMLInputButtonElement;
                            if (inputSubmit != null)
                            {
                                if (inputSubmit.type.Equals(Properties.Resources.InputSubmit, StringComparison.OrdinalIgnoreCase))
                                {
                                    inputSubmit.click();
                                }
                            }
                        }
                    }
                }
            }
        }

        private void NavigateLogoutPage()
        {
            this.webBrowser.Navigate(new Uri(Properties.Resources.MeilishuoLogoutUri, UriKind.RelativeOrAbsolute));
        }

        private void NavigatePage(string uri)
        {
            this.webBrowser.Navigate(new Uri(uri, UriKind.RelativeOrAbsolute));
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.dataGridUser.ItemsSource = this.userTable;
            this.dataGridUri.ItemsSource = this.uriTable;            
            this.dataGridUserUri.ItemsSource = this.useruriTable;

            timer = new DispatcherTimer();
            timer.Tick += timer_Tick;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            this.timer.Stop();

            if (this.currentWorkflowStepIndex < 0 || this.currentWorkflowStepIndex >= this.listWorkflowStep.Count)
            {
                this.currentWorkflowStepIndex = 0;
            }

            if (this.listWorkflowStep[this.currentWorkflowStepIndex].WaitBrowserLoaded)
            {
                if (!this.webBrowserLoaded)
                {
                    this.timer.Start();
                    return;
                }

                this.webBrowserLoaded = false;
            }

            this.timer.Interval = TimeSpan.FromSeconds(Convert.ToInt32(this.textBoxTimerInterval.Text) * this.listWorkflowStep[this.currentWorkflowStepIndex].TimerFactor);

            switch (this.listWorkflowStep[this.currentWorkflowStepIndex].Step)
            {
                case WorkflowStep.BookLike:
                    this.BookLike();
                    break;
                case WorkflowStep.FillAndLogin:
                    this.FillAndLogin(this.username, this.password);
                    break;
                case WorkflowStep.NavigateLogout:
                    this.NavigateLogoutPage();
                    break;
                case WorkflowStep.NavigateTarget:
                    this.NavigateTargetPage(this.targetUri);
                    break;
                case WorkflowStep.SelectTarget:
                    if (0 <= this.currentWorkItemIndex && this.currentWorkItemIndex < this.listUseruri.Count)
                    {
                        RandomClickDataSetTableAdapters.userTableAdapter userAdapter =
                            new RandomClickDataSetTableAdapters.userTableAdapter();
                        RandomClickDataSet.userDataTable userTable = userAdapter.GetDataByUsername(this.listUseruri[this.currentWorkItemIndex].username);
                        if (userTable.Rows.Count > 0)
                        {
                            RandomClickDataSet.userRow userRow = userTable.Rows[0] as RandomClickDataSet.userRow;
                            if (userRow != null)
                            {
                                this.username = this.listUseruri[this.currentWorkItemIndex].username;
                                this.password = userRow.password;
                                this.activeLink = userRow.activelink;
                                this.targetUri = this.listUseruri[this.currentWorkItemIndex].uri;
                                
                                if (Properties.Resources.UriStateTodo.Equals(this.listUseruri[this.currentWorkItemIndex].uristate, StringComparison.OrdinalIgnoreCase))
                                {
                                    if (string.IsNullOrEmpty(this.activeLink))
                                    {
                                        this.listWorkflowStep = this.GetMeilishuoBookLikeUsernamePasswordWorkflow();
                                    }
                                    else
                                    {
                                        this.listWorkflowStep = this.GetMeilishuoBookLikeActiveLinkWorkflow();
                                    }                                    
                                }
                                else if (Properties.Resources.UriStateDone.Equals(this.listUseruri[this.currentWorkItemIndex].uristate, StringComparison.OrdinalIgnoreCase))
                                {
                                    if (string.IsNullOrEmpty(this.activeLink))
                                    {
                                        this.MeilishuoCheckUriUsernamePasswordWorkflow();
                                    }
                                    else
                                    {
                                        this.MeilishuoCheckUriActiveLinkWorkflow();
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(@"No more. Done");
                    }
                    break;
                case WorkflowStep.FinishTarget:
                    RandomClickDataSetTableAdapters.useruriTableAdapter useruriAdatper =
                        new RandomClickDataSetTableAdapters.useruriTableAdapter();
                    if (Properties.Resources.UriStateTodo.Equals(this.listUseruri[this.currentWorkItemIndex].uristate, StringComparison.OrdinalIgnoreCase))
                    {
                        this.listUseruri[this.currentWorkItemIndex].uristate = Properties.Resources.UriStateDone;                        
                    }
                    else if (Properties.Resources.UriStateDone.Equals(this.listUseruri[this.currentWorkItemIndex].uristate, StringComparison.OrdinalIgnoreCase))
                    {
                        this.listUseruri[this.currentWorkItemIndex].uristate = Properties.Resources.UriStateCheck;
                    }
                    useruriAdatper.Update(this.listUseruri[this.currentWorkItemIndex]);
                    this.currentWorkItemIndex++;

                    if (this.toStop)
                    {
                        MessageBox.Show(@"Stopped");
                        return;
                    }
                    break;
                case WorkflowStep.NavigateActiveLink:
                    this.NavigateTargetPage(this.activeLink);
                    break;
                case WorkflowStep.NavigateHome:
                    this.NavigateTargetPage(Properties.Resources.MeilishuoUri);
                    break;
                default:
                    break;
            }

            this.currentWorkflowStepIndex++;

            this.timer.Start();
        }

        private void buttonAddUser_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.textBoxUsername.Text) ||
                string.IsNullOrEmpty(this.textBoxPassword.Text) ||
                string.IsNullOrEmpty(this.textBoxEmail.Text))
            {
                MessageBox.Show(@"Please input username password activelink email");
                return;
            }

            RandomClickDataSetTableAdapters.userTableAdapter userAdapter =
                new RandomClickDataSetTableAdapters.userTableAdapter();
            if (userAdapter.GetDataByUsername(this.textBoxUsername.Text).Rows.Count > 0)
            {
                MessageBox.Show(@"Username exists");
                return;
            }

            userAdapter.Insert(this.textBoxUsername.Text, this.textBoxPassword.Text, Properties.Resources.UserStateValid, 
                DateTime.Now, this.textBoxActiveLink.Text, this.textBoxEmail.Text);

            this.userTable = userAdapter.GetData();
            this.labelUserCount.Content = this.userTable.Rows.Count;
            this.dataGridUser.ItemsSource = this.userTable;
        }

        private void buttonDeleteUser_Click(object sender, RoutedEventArgs e)
        {
            if (this.dataGridUser.SelectedIndex >= 0 && this.dataGridUser.SelectedIndex < this.userTable.Rows.Count)
            {
                RandomClickDataSet.userRow userRow = this.userTable.Rows[this.dataGridUser.SelectedIndex] as RandomClickDataSet.userRow;
                if (userRow == null)
                {
                    return;
                }

                RandomClickDataSetTableAdapters.useruriTableAdapter useruriAdapter = 
                    new RandomClickDataSetTableAdapters.useruriTableAdapter();
                useruriAdapter.DeleteQueryByUsername(userRow.username);
                this.useruriTable = useruriAdapter.GetDataByUristate(Properties.Resources.UriStateTodo);
                this.dataGridUserUri.ItemsSource = this.useruriTable;
                
                userRow.userstate = Properties.Resources.UserStateDeleted;

                RandomClickDataSetTableAdapters.userTableAdapter userAdapter =
                    new RandomClickDataSetTableAdapters.userTableAdapter();
                userAdapter.Update(userRow);
            }
            else
            {
                MessageBox.Show(@"Please select one user");
            }
        }

        private void buttonUpdateUser_Click(object sender, RoutedEventArgs e)
        {
            if (this.dataGridUser.SelectedIndex >= 0 && this.dataGridUser.SelectedIndex < this.userTable.Rows.Count)
            {
                if (string.IsNullOrEmpty(this.textBoxPassword.Text) ||
                    string.IsNullOrEmpty(this.textBoxEmail.Text))
                {
                    MessageBox.Show(@"Please input password activelink email");
                    return;
                }

                RandomClickDataSet.userRow userRow = this.userTable.Rows[this.dataGridUser.SelectedIndex] as RandomClickDataSet.userRow;
                if (userRow == null)
                {
                    return;
                }

                userRow.password = this.textBoxPassword.Text;
                userRow.activelink = this.textBoxActiveLink.Text;
                userRow.email = this.textBoxEmail.Text;

                RandomClickDataSetTableAdapters.userTableAdapter userAdapter =
                    new RandomClickDataSetTableAdapters.userTableAdapter();

                userAdapter.Update(userRow);
            }
            else
            {
                MessageBox.Show(@"Please select one user");
            }
        }

        private void dataGridUser_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.dataGridUser.SelectedIndex >= 0 && this.dataGridUser.SelectedIndex < this.userTable.Rows.Count)
            {
                RandomClickDataSet.userRow userRow = this.userTable.Rows[this.dataGridUser.SelectedIndex] as RandomClickDataSet.userRow;
                if (userRow != null)
                {
                    this.textBoxUsername.Text = userRow.username;
                    this.textBoxPassword.Text = userRow.password;
                    this.textBoxActiveLink.Text = userRow.activelink;

                    string rowFilter = string.Format(@"username = '{0}'", userRow.username);
                    this.useruriTable.DefaultView.RowFilter = rowFilter;
                }
            }
        }

        private void buttonClearUserSelection_Click(object sender, RoutedEventArgs e)
        {
            this.dataGridUser.SelectedIndex = -1;
            this.textBoxUsername.Text = string.Empty;
            this.textBoxPassword.Text = string.Empty;
            this.textBoxActiveLink.Text = string.Empty;
            this.textBoxEmail.Text = string.Empty;
            this.useruriTable.DefaultView.RowFilter = string.Empty;
        }

        private void buttonAddUri_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.textBoxUri.Text) ||
                string.IsNullOrEmpty(this.textBoxUsernumber.Text))
            {
                MessageBox.Show(@"Please input uri usernumber");
                return;
            }  

            int usernumber = Convert.ToInt32(this.textBoxUsernumber.Text);

            if (usernumber <= 0)
            {
                MessageBox.Show(@"Wrong usernumber");
                return;
            }            

            if (!this.CheckSupportUri(this.textBoxUri.Text))
            {
                MessageBox.Show(@"Uri do not support");
                return;
            }
            
            RandomClickDataSetTableAdapters.uriTableAdapter uriAdapter =
                new RandomClickDataSetTableAdapters.uriTableAdapter();
            //if (uriAdapter.GetDataByUri(this.textBoxUri.Text).Rows.Count > 0)
            //{
            //    MessageBox.Show(@"Uri exists");
            //    return;
            //}

            if (usernumber > this.userTable.Rows.Count)
            {
                MessageBox.Show(@"Not enough user");
                return;
            }

            if (!this.GenerateUserUri(this.textBoxUri.Text, usernumber))
            {
                MessageBox.Show(@"Generate useruri fail. Please add uri again");
                return;
            }

            uriAdapter.Insert(this.textBoxUri.Text, usernumber);

            this.uriTable = uriAdapter.GetData();
            this.dataGridUri.ItemsSource = this.uriTable;
        }

        private bool CheckSupportUri(string uri)
        {
            RandomClickDataSetTableAdapters.rooturiTableAdapter rooturiAdapter =
                new RandomClickDataSetTableAdapters.rooturiTableAdapter();
            RandomClickDataSet.rooturiDataTable rooturiTable = rooturiAdapter.GetData();
            foreach (RandomClickDataSet.rooturiRow rooturiRow in rooturiTable.Rows)
            {
                if (uri.Contains(rooturiRow.rooturi))
                {
                    return true;
                }
            }

            return false;
        }

        private bool GenerateUserUri(string uri, int usernumber)
        {
            RandomClickDataSetTableAdapters.useruriTableAdapter useruriAdatper = 
                new RandomClickDataSetTableAdapters.useruriTableAdapter();
            for (int i = 0; i < usernumber; ++i)
            {
                RandomClickDataSet.userRow userRow = this.userTable.Rows[i] as RandomClickDataSet.userRow;
                if (userRow != null)
                {
                    if (useruriAdatper.GetDataByUsernameUri(userRow.username, uri).Rows.Count > 0)
                    {
                        continue;
                    }

                    useruriAdatper.Insert(userRow.username, uri, Properties.Resources.UriStateTodo, DateTime.Now);
                }
                else
                {
                    return false;
                }
            }

            this.useruriTable = useruriAdatper.GetData();
            this.dataGridUserUri.ItemsSource = this.useruriTable;
            return true;
        }

        private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            try
            {
                Convert.ToInt32(e.Text);
            }
            catch
            {
                e.Handled = true;
            }
        }

        private void TextBoxPastingEventHandler(object sender, DataObjectPastingEventArgs e)
        {
            string clipboard = e.DataObject.GetData(typeof(string)) as string;
            try
            {
                Convert.ToInt32(clipboard);
            }
            catch
            {
                e.CancelCommand();
                e.Handled = true;
            }
        }

        private void buttonClearUriSelection_Click(object sender, RoutedEventArgs e)
        {
            this.dataGridUri.SelectedIndex = -1;
            this.useruriTable.DefaultView.RowFilter = string.Empty;
        }

        private void dataGridUri_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string rowFilter = string.Empty;
            for (int i = 0; i < this.dataGridUri.SelectedItems.Count; i++)
            {
                int itemIndex = this.dataGridUri.Items.IndexOf(this.dataGridUri.SelectedItems[i]);

                if (itemIndex >= 0 && itemIndex < this.uriTable.Rows.Count)
                {
                    RandomClickDataSet.uriRow uriRow = this.uriTable.Rows[itemIndex] as RandomClickDataSet.uriRow;
                    if (uriRow != null)
                    {
                        this.textBoxUri.Text = uriRow.uri;

                        if (string.IsNullOrEmpty(rowFilter))
                        {
                            rowFilter = string.Format(@"uri = '{0}'", uriRow.uri);
                        }
                        else
                        {
                            rowFilter += @" OR ";
                            rowFilter += string.Format(@"uri = '{0}'", uriRow.uri);
                        }
                    }
                }
            }
            this.useruriTable.DefaultView.RowFilter = rowFilter;
        }

        private void buttonStartAll_Click(object sender, RoutedEventArgs e)
        {
            this.PrepareStartTask(Properties.Resources.UriStateTodo);

            timer.Start();
        }

        private void PrepareStartTask(string taskMode)
        {
            if (string.IsNullOrEmpty(this.textBoxTimerInterval.Text))
            {
                MessageBox.Show(@"Please input timer interval");
                return;
            }

            int timerInterval = Convert.ToInt32(this.textBoxTimerInterval.Text);
            if (timerInterval < 5)
            {
                MessageBox.Show(@"Timer interval > 5");
                return;
            }

            timer.Interval = TimeSpan.FromSeconds(timerInterval);
            this.taskMode = taskMode;
            RandomClickDataSetTableAdapters.useruriTableAdapter useruriAdatper =
                new RandomClickDataSetTableAdapters.useruriTableAdapter();
            this.useruriTable = useruriAdatper.GetDataByUristate(this.taskMode);
            this.dataGridUserUri.ItemsSource = this.useruriTable;

            this.listUseruri.Clear();
            foreach (RandomClickDataSet.useruriRow item in this.useruriTable.Rows)
            {
                this.listUseruri.Add(item);
            }

            this.currentWorkItemIndex = 0;
            this.currentWorkflowStepIndex = -1;
            this.toStop = false;
        }

        private void buttonStopAll_Click(object sender, RoutedEventArgs e)
        {
            this.toStop = true;
        }

        private void buttonGoTest_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.textBoxUri.Text))
            {
                MessageBox.Show(@"Please input uri");
                return;
            }  

            this.NavigatePage(this.textBoxUri.Text);
        }

        private void buttonFillLoginTest_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.textBoxUsername.Text) ||
                string.IsNullOrEmpty(this.textBoxPassword.Text))
            {
                MessageBox.Show(@"Please input username and password");
                return;
            }
            
            this.FillAndLogin(this.textBoxUsername.Text, this.textBoxPassword.Text);
        }

        private void buttonLogoutTest_Click(object sender, RoutedEventArgs e)
        {
            this.NavigateLogoutPage();
        }

        private void buttonBookLikeTest_Click(object sender, RoutedEventArgs e)
        {
            this.BookLike();
        }

        private void webBrowser_LoadCompleted(object sender, NavigationEventArgs e)
        {
            this.webBrowserLoaded = true;
        }

        private void buttonToggleWeb_Click(object sender, RoutedEventArgs e)
        {
            if (this.webBrowser.Visibility == Visibility.Hidden)
            {
                this.webBrowser.Visibility = Visibility.Visible;
            }
            else
            {
                this.webBrowser.Visibility = Visibility.Hidden;
            }
        }

        private void buttonActiveLinkTest_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.textBoxActiveLink.Text))
            {
                MessageBox.Show(@"Please input activelink");
                return;
            }

            this.NavigatePage(this.textBoxActiveLink.Text);
        }

        private void buttonPause_Click(object sender, RoutedEventArgs e)
        {
            this.timer.Stop();
        }

        private void buttonResume_Click(object sender, RoutedEventArgs e)
        {
            this.timer.Start();
        }

        private void buttonRefreshTest_Click(object sender, RoutedEventArgs e)
        {
            this.webBrowser.Refresh();
        }

        private void buttonCheckUriState_Click(object sender, RoutedEventArgs e)
        {
            this.PrepareStartTask(Properties.Resources.UriStateDone);

            timer.Start();
        }

        private void buttonRedoUri_Click(object sender, RoutedEventArgs e)
        {
            foreach (DataRowView rowView in this.dataGridUri.SelectedItems)
            {
                RandomClickDataSet.uriRow uriRow = rowView.Row as RandomClickDataSet.uriRow;
                RandomClickDataSetTableAdapters.useruriTableAdapter useruriAdapter =
                    new RandomClickDataSetTableAdapters.useruriTableAdapter();
                useruriAdapter.UpdateQueryByUriState(Properties.Resources.UriStateTodo, DateTime.Now, uriRow.uri);
                this.useruriTable = useruriAdapter.GetDataByUristate(Properties.Resources.UriStateTodo);
                this.dataGridUserUri.ItemsSource = this.useruriTable;
            }
        }

        private void textBoxTimerInterval_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.textBoxTimerInterval.Text))
            {
                int totalTimeFactor = 0;
                List<WorkflowStepInfo> listWFStep = this.GetMeilishuoBookLikeUsernamePasswordWorkflow();
                foreach (WorkflowStepInfo item in listWFStep)
                {
                    totalTimeFactor += item.TimerFactor;
                }

                this.labelTotalTime.Content = totalTimeFactor * Convert.ToInt32(this.textBoxTimerInterval.Text);
            }
        }
    }
}
